package com.hj.dapp.business.mainbudget.service.impl;

import com.hj.dapp.business.budget.model.Budget;
import com.hj.dapp.business.budget.service.BudgetService;
import com.hj.dapp.business.category.model.Category;
import com.hj.dapp.business.customer.model.IntendedCustomer;
import com.hj.dapp.business.customer.service.IntendedCustomerService;
import com.hj.dapp.business.engineer.model.EngineerProject;
import com.hj.dapp.business.engineer.service.EngineerProjectService;
import com.hj.dapp.business.mainbudget.mapper.MainBudgetMapper;
import com.hj.dapp.business.mainbudget.model.MainBudget;
import com.hj.dapp.business.mainbudget.model.MainBudgetItem;
import com.hj.dapp.business.mainbudget.service.MainBudgetItemService;
import com.hj.dapp.business.mainbudget.service.MainBudgetService;
import com.hj.dapp.business.mainbudget.vo.MainBudgetSaveItem;
import com.hj.dapp.business.mainbudget.vo.MainBudgetSaveVO;
import com.hj.dapp.business.mainbudget.vo.MainBudgetUnits;
import com.hj.dapp.business.user.model.User;
import com.hj.dapp.business.user.service.UserService;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletOutputStream;
import javax.validation.constraints.Min;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * @author 胡奥程
 * @version 1.0
 * @date 2024/1/29
 */
@Service
public class MainBudgetServiceImpl implements MainBudgetService {
    @Autowired
    private MainBudgetMapper mainBudgetMapper;
    @Autowired
    private IntendedCustomerService intendedCustomerService;
    @Autowired
    private EngineerProjectService engineerProjectService;
    @Autowired
    private UserService userService;
    @Autowired
    private MainBudgetItemService mainBudgetItemService;
    @Autowired
    private BudgetService budgetService;

    @Override
    public void save(MainBudgetSaveVO mainBudgetSaveVO) {
        MainBudget mainBudget = get(mainBudgetSaveVO.getMainBudgetId());
        if (ObjectUtils.isEmpty(mainBudget)) {
            IntendedCustomer customer = intendedCustomerService.get(mainBudgetSaveVO.getCustomerId());
            /*保存主表数据*/
             mainBudget = new MainBudget();
            /*保存客户信息*/
            mainBudget.setCustomerId(mainBudgetSaveVO.getCustomerId());
            mainBudget.setCustomerPhone(customer.getPhone());
            mainBudget.setCustomerName(customer.getName());
            /*保存工程信息*/
            mainBudget.setEngineerProjectId(mainBudgetSaveVO.getEngineerProjectId());
            EngineerProject engineerProject = engineerProjectService.get(mainBudgetSaveVO.getEngineerProjectId());
            mainBudget.setEngineerAddress(engineerProject.getAddress());
            mainBudget.setEngineerName(engineerProject.getAddress());
            /*保存审核人员信息*/
            User reviewer = userService.getUserById(customer.getReviewerId());
            mainBudget.setReviewerId(reviewer.getId());
            mainBudget.setReviewerName(reviewer.getRealName());
            /*保存监理人员信息*/
            User supervisor = userService.getUserById(customer.getSupervisorId());
            mainBudget.setSupervisorId(supervisor.getId());
            mainBudget.setSupervisorName(supervisor.getRealName());
            /*保存设计师信息*/
            User designer = userService.getUserById(customer.getDesignerId());
            mainBudget.setDesignerId(designer.getId());
            mainBudget.setDesignerName(designer.getRealName());
            mainBudget.setDesignerPhone(designer.getPhone());
            mainBudgetMapper.insert(mainBudget);
        }
        MainBudget finalMainBudget = mainBudget;
        mainBudgetItemService.deleteRel(mainBudget.getId());
        List<MainBudgetSaveItem> items = mainBudgetSaveVO.getItems();
        items.forEach(n -> {
            List<MainBudgetUnits> budgetUnits = n.getBudgetUnits();
            if (!ObjectUtils.isEmpty(budgetUnits)) {
                budgetUnits.forEach(k -> {
                    MainBudgetItem mainBudgetItem = new MainBudgetItem();
                    BeanUtils.copyProperties(k, mainBudgetItem);
                    mainBudgetItem.setTotalPrice(mainBudgetItem.getNum().multiply(mainBudgetItem.getSalePrice()));
                    mainBudgetItem.setMainBudgetId(finalMainBudget.getId());
                    mainBudgetItemService.save(mainBudgetItem);
                });
            }
        });

    }

    @Override
    public MainBudget get(Long id) {
        return mainBudgetMapper.selectById(id);
    }

    @Override
    public MainBudgetSaveVO getMainBudget(Long customerId, Long engineerProjectId) {
        return mainBudgetMapper.getMainBudget(customerId, engineerProjectId);

    }

    @Override
    public List<Category> getBindCategorys(Long mainBudgetId) {
        return mainBudgetMapper.getBindCategorys(mainBudgetId);
    }

    @Override
    public void exportMainBudget(Long customerId, Long engineerProjectId, ServletOutputStream outputStream) {
        MainBudgetSaveVO mainBudget = getMainBudget(customerId, engineerProjectId);
        /*计算主材合计*/
        final BigDecimal[] mainTotalPrice = {BigDecimal.ZERO};
        mainBudget.getItems().forEach(n->{
            BigDecimal reduce = n.getBudgetUnits().stream().map(MainBudgetUnits::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            n.setTotalPrice(reduce);
            mainTotalPrice[0] =  mainTotalPrice[0].add(reduce);
        });
        mainBudget.setMainTotalPrice(mainTotalPrice[0]);
        /*计算主材折后价*/
        EngineerProject engineerProject = engineerProjectService.get(engineerProjectId);
        BigDecimal mainDiscountRate = engineerProject.getMainDiscountRate();
        mainBudget.setMainDiscountPrice(mainTotalPrice[0].multiply(mainDiscountRate).setScale(2, RoundingMode.HALF_UP));
        /*计算轻辅最终价格*/
        BigDecimal lightDiscountPrice = budgetService.getDiscountPrice(customerId, engineerProjectId);
        mainBudget.setLightFinalPrice(lightDiscountPrice.setScale(2,RoundingMode.HALF_UP));
        /*计算合同价款*/
        mainBudget.setContactPrice(mainBudget.getMainDiscountPrice().add(lightDiscountPrice).setScale(2,RoundingMode.HALF_UP));
        InputStream is = null;
        try {
            ClassLoader loader = this.getClass().getClassLoader();
            is = loader.getResourceAsStream("classpath:template-m.xlsx");
            if (ObjectUtils.isEmpty(is)) {
                ClassPathResource classPathResource = new ClassPathResource("template-m.xlsx");
                is = classPathResource.getInputStream();
            }
            Context context = new Context();
            context.putVar("mainBudget", mainBudget);
            JxlsHelper.getInstance().processTemplate(is, outputStream, context);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
